<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "insurance_plan".
 *
 * @property integer $plan_id
 * @property string $plan_code
 * @property string $project_code
 * @property string $plan_name
 * @property string $plan_tag
 * @property string $plan_desc
 * @property string $ctime
 * @property string $status
 */
class InsurancePlan extends \yii\db\ActiveRecord
{
    const STATUS_SUCCESS = 'ok';

    /**
     * 筛选出所有满足条件的计划
     */
    public static function getInsurancePlanList($where=''){
        $filter = "1=1";
        if ($where) {
            if(@stripos($where, "_")){
                $filter = sprintf("a.project_code in ('%s')",str_replace('_',"','",$where));
            }else{
                $filter = sprintf("a.project_code='%s'",$where);    
            }
        }
        return static::find()->from(self::tableName() . ' as a')
            ->leftJoin(InsuranceProject::tableName() . ' as b', 'a.project_code = b.project_code')
            ->andWhere(['a.status' => static::STATUS_SUCCESS])
            ->andWhere($filter)
            ->select(['a.plan_fullname','a.plan_desc','a.project_code','a.plan_code','b.project_name','b.provider_id','b.min_amount','b.project_desc','a.min_price'])
            ->orderBy(['a.plan_id' => SORT_DESC ,'a.plan_order' => SORT_DESC])->limit(20)->asArray()->all();

            // $model->find()->createCommand()->getRawSql();
    }

    /**
     * 获取根据用户选择的计划 code 查询产品相关信息
     */
    public static function getInsuranceByPlanCode($plan_code){
        return static::find()->from(self::tableName() . ' as a')
            ->leftJoin(InsuranceProject::tableName() . ' as b', 'a.project_code = b.project_code')
            ->where(['a.plan_code' => $plan_code])
            ->andWhere(['a.status' => static::STATUS_SUCCESS])
            ->orderBy('a.id asc')->asArray()->all();
    }
    
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'insurance_plan';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ctime'], 'safe'],
            [['plan_code', 'project_code', 'plan_tag'], 'string', 'max' => 32],
            [['plan_name'], 'string', 'max' => 128],
            [['plan_desc'], 'string', 'max' => 256],
            [['status'], 'string', 'max' => 16],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'plan_id' => 'Plan ID',
            'plan_code' => 'Plan Code',
            'project_code' => 'Project Code',
            'plan_name' => 'Plan Name',
            'plan_tag' => 'Plan Tag',
            'plan_desc' => 'Plan Desc',
            'ctime' => 'Ctime',
            'status' => 'Status',
        ];
    }


}
